#!/usr/bin/python
import serial
import time
ser = serial.Serial('/dev/ttyAMA0',baudrate=9600)
print(ser.isOpen())
ser.write(b'\x66')

import numpy as np  #导入科学计算库numpy
import cv2 as cv  #导入opencv-python
#打开捕获器（0-系统默认摄像头）
j = 0
cap = cv.VideoCapture(0,cv.CAP_V4L2)
#打开失败
if not cap.isOpened():
    print("Cannot open camera")
    exit()
print("摄像头开启\n")
while 1:     
    data = ser.read(1)
    if data == b'\x66':
        print("Start")
        num = 0     #识别10次
        ci = 0      #雌次数
        xiong = 0   #雄次数
        #打开成功
        while num < 9:  #识别9次
            #如果正确读取帧，ret为True
            ret, frame = cap.read()
            #读取失败，则退出循环
            if not ret:
                print("Can't receive frame (stream end?). Exiting ...")
                break
            #图像处理-转换为灰度图
            aim = cv.rectangle(frame,(200,100),(450,350),(0,0,255),3)
            mask = np.zeros(frame.shape[:2],np.uint8)
            mask[100:350,200:450] = 1
            feature = cv.bitwise_and(frame,frame,mask = mask)
            #画准心
            #下面是帧图像处理,处理完后都是在thresh上操作
            img_gray = cv.cvtColor(feature, cv.COLOR_BGR2GRAY)
            ret1, img_difference1 = cv.threshold(img_gray, 210, 255, cv.THRESH_TOZERO_INV)
            ret2, img_difference2 = cv.threshold(img_gray, 230, 255, cv.THRESH_TOZERO_INV)
            thresh_a = img_difference2 - img_difference1
            thresh = cv.GaussianBlur(thresh_a, (5, 5), 0)
            # 腐蚀
            kernel = np.ones((5, 5))
            res_erosion = cv.erode(thresh, kernel, iterations=2)
            res_dilation = cv.dilate(res_erosion, kernel, iterations=2)
            res = cv.erode(res_dilation, kernel, iterations=4)
            #
            contours, hierarchy = cv.findContours(res, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
            img_copy1 = feature.copy()
            img_copy2 = feature.copy()

            if len(contours)>0:
             contour = []
             for cont in contours:
                contour.extend(cont)
             min_rect = cv.minAreaRect(np.array(contour))
             box = cv.boxPoints(min_rect)
             box2 = np.int0(box)
             img_contours1 = cv.drawContours(img_copy1, [box2], -1, (255, 0, 0), 2)
             if len(contours)==1:
                 print(0)
                 ci+=1  #雌蕊加1
             else:
                 print(1)
                 xiong+=1   #雄蕊加1
            else:
                continue
            img_contours2 = cv.drawContours(img_copy2, contours, -1, (255, 0, 0), 2)

            #显示画面
            #cv.imshow('aim', img_contours2)
            #cv.namedWindow("thresh",0)
            #cv.resizeWindow("thresh",400,400)
            #cv.imshow('thresh',res)
            
            key_pressed = cv.waitKey(1000)
                #如果按下esc键，就退出循环
            if key_pressed == 27:
                cap.release()  #释放捕获器
                #cv.destroyAllWindows() #关闭图像窗口
                #a = frame.shape[:2]
                #print(a)
                print("释放摄像头")
                break
            num+=1

        if ci>xiong:
            print("雌蕊")
            ser.write(b"\x11")
        else:
            print("雄蕊")
            ser.write(b"\x22")
        ser.flushInput()

